<template>
	<view class="curriculumManagement">
		<view class="section-title">
			<view class="title-display">
				今日课程管理
			</view>
			<view class="date-display">
				{{currentDate}}
			</view>
		</view>

		<view class="tabs">
			<view class="tab" v-for="(item,index) in tabs" :key="index"
				:class="{ 'booking-tab-active': activeTabIndex === index }" @click="selectTab(index)">
				{{item}}
			</view>
		</view>

		<!-- 如果当前没有课程数据，显示无数据提示 -->
		<view class="empty-data" v-if="courses.length === 0">
			暂无对应课程
		</view>

		<!-- 使用v-for渲染课程列表 -->
		<view class="coursesList" v-else v-for="(course, courseIndex) in courses" :key="course.id">
			<view class="course-header">
				<view class="course-title">
					{{course.name}}
				</view>
				<!-- 待上课#2196F3 上课中#4CAF50  已结束#9E9E9E -->
				<view class="course-status" :style="'background-color:' + getCourseStatusColor(course.status)">
					{{getCourseStatusText(course.status)}}
				</view>
			</view>

			<view class="course-info">
				<view class="">
					时间： {{formatTime(course.startTime)}}-{{formatTime(course.endTime)}}
				</view>
				<view class="">
					地点： {{course.address || '未设置'}}
				</view>
			</view>
			<view class="course-info">
				<view class="">
					类型: {{course.categoriesName || '未分类'}}
				</view>
				<view class="">
					人数: {{course.quantity || 0}}/{{course.maxCapacity}}
				</view>
			</view>

			<!-- 显示学员列表，仅在有学员时显示 -->
			<view class="student-list" v-if="course.quantity && course.quantity > 0">
				<view class="student-item" v-for="(student, studentIndex) in course.userName" :key="studentIndex">
					<view class="student-name">
						<image class="student-avator" :src="student.avatar" mode="center"></image>
						{{student.nickname}}
					</view>
					<view class="student-status">
						{{student.sign_in == 0 ? '未签到' : '已签到'}}
					</view>
				</view>
			</view>

			<view v-else class="empty-student-msg">
				暂无学员报名
			</view>
			<!-- 课程操作按钮 -->
			<view class="course-actions">
				<view class="btn" v-if="course.status == '1'" @click="startCourse(course.id)">
					开始上课
				</view>
				<view class="btn" v-else-if="course.status == '2'" @click="endCourse(course.id)">
					结束课程
				</view>
				<view class="btn" v-if="course.reportStatus" @click="trainingReportsClick(course)"
					style="width: 200rpx;">
					填写训练报告
				</view>
				<!-- <view class="btn" v-else @click="viewCourseDetail(course.id)">
					查看详情
				</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getToken
	} from '@/utils/auth.js';

	export default {
		data() {
			return {
				activeTabIndex: 0,
				tabs: ['全部课程', '待上课', '上课中', '已完成'],
				courses: [], // 所有课程数据
				currentDate: '' // 当前日期
			}
		},
		onLoad() {
			// 获取课程列表（默认全部课程）
			this.getCourseList();
		},
		methods: {
			// 获取课程列表
			getCourseList(status) {
				// 清空当前数据
				this.courses = [];

				const data = {
					openid: getToken()
				};

				// 如果传入了status参数，则添加到请求参数
				if (status) {
					data.status = status;
				}
				// 调试信息
				console.log("请求参数:", data);

				this.request('gym/courseCategories/list', data, 'GET').then(res => {
					this.courses = res.data;
					// 按照开始时间排序
					// this.courses.sort((a, b) => {
					//     return new Date(a.startTime) - new Date(b.startTime);
					// });

				})
			},

			// 获取课程状态文本
			getCourseStatusText(status) {
				const statusMap = {
					'1': '待上课',
					'2': '上课中',
					'3': '已结束'
				};

				return statusMap[status] || '未知状态';
			},

			// 获取课程状态颜色
			getCourseStatusColor(status) {
				const colorMap = {
					'1': '#2196F3', // 蓝色 - 待上课
					'2': '#4CAF50', // 绿色 - 进行中
					'3': '#9E9E9E' // 灰色 - 已结束
				};

				return colorMap[status] || '#2196F3';
			},

			// 格式化时间为 HH:MM 格式
			formatTime(dateTimeStr) {
				if (!dateTimeStr) return '';

				try {
					const date = new Date(dateTimeStr);
					if (isNaN(date.getTime())) {
						return '时间格式错误';
					}
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					return `${hours}:${minutes}`;
				} catch (error) {
					console.error('时间格式化错误:', error);
					return '时间格式错误';
				}
			},

			// 开始上课
			startCourse(courseId) {
				// 获取当前课程数据
				const currentCourse = this.courses.find(c => c.id === courseId);

				// 检查课程是否有学员
				if (!currentCourse.quantity || currentCourse.quantity <= 0) {
					uni.showToast({
						title: '请等待学生加入后再开启该课程',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				uni.showModal({
					title: '确认开始',
					content: '确定要开始这节课程吗？',
					success: res => {
						if (res.confirm) {
							// 调用开始上课API
							const data = {
								id: courseId
							};
							this.request('gym/courseClass/list', data, 'GET').then(res => {
								console.log("开始上课结果:", res);

								uni.showToast({
									title: '课程已开始',
									icon: 'success'
								});

								// 重新加载当前状态的课程列表
								this.selectTab(this.activeTabIndex);
							})
						}
					}
				});
			},
			// 结束课程
			endCourse(courseId) {
				uni.showModal({
					title: '确认结束',
					content: '确定要结束这节课程吗？',
					success: res => {
						if (res.confirm) {
							const data = {
								id: courseId
							};
							this.request('gym/courseClassStop/list', data, 'GET').then(res => {
								console.log("结束课程:", res);
								uni.showToast({
									title: '课程已结束',
									icon: 'success'
								});

								// 可选：重新加载当前状态的课程列表
								this.selectTab(this.activeTabIndex);
							})
						}
					}
				});
			},
			/* 训练报告 */
			trainingReportsClick(course) {
				console.log("打印一下", course);

				// 需要将课程对象序列化并进行URL编码
				const courseParam = encodeURIComponent(JSON.stringify(course));

				// 导航到训练报告页面，传递编码后的课程数据
				uni.navigateTo({
					url: '/pages/trainingReports?courseData=' + courseParam
				});
			},
			// 切换标签
			selectTab(index) {
				this.activeTabIndex = index;

				// 根据选中的标签调用不同状态的API
				if (index === 0) {
					// 全部课程，不传status参数
					this.getCourseList();
				} else {
					// 根据选中的标签加载对应状态的课程
					const statusMap = {
						1: '1', // 待上课
						2: '2', // 上课中
						3: '3' // 已完成
					};
					this.getCourseList(statusMap[index]);
				}
			}
		}
	}
</script>

<style lang="scss">
	@import '@/common/mixins.scss';

	// @include rounded-box(32upx);
	// @include box-sizing-padding(24upx);
	// @include flex-center(center, space-between, column);

	.empty-data {
		width: 100%;
		padding: 40rpx 0;
		text-align: center;
		color: #999;
		font-size: 30rpx;
		margin-top: 30rpx;
		background-color: #1f1f1f;
		@include rounded-box(20rpx);
		@include box-sizing-padding(24upx);
	}

	.course-actions {
		width: 100%;
		@include flex-center(center, flex-end);
		margin: 20rpx auto 0;

		.btn {
			width: 172rpx;
			height: 70rpx;
			@include rounded-box(20upx, #FFD700);
			@include flex-center();
			color: #000;
			font-weight: bold;
		}
	}

	.coursesList {
		width: 100%;
		min-height: 300rpx;
		@include rounded-box(20rpx, #1f1f1f);
		@include box-sizing-padding(24upx);
		margin-bottom: 40rpx;

		.empty-student-msg {
			width: 100%;
			min-height: 200rpx;
			font-size: 30rpx;
			color: #fff;
			@include flex-center(center);
			@include rounded-box(16rpx, #2a2a2a);
		}

		.student-list {
			width: 100%;
			min-height: 200rpx;
			@include rounded-box(16rpx, #2a2a2a);
			@include box-sizing-padding(20rpx);
			@include flex-center(center, space-between, column);
			margin: 25rpx auto;

			.student-item {
				width: 100%;
				padding: 25rpx 0;
				@include flex-center(center, space-between);
				border-bottom: 1px solid #444;

				&:last-child {
					border-bottom: none;
				}
			}

			.student-status {
				font-size: 24rpx;
				color: #aaa;
			}

			.student-name {
				color: #fff;
				font-size: 32rpx;
				@include flex-center(center, left);

				.student-avator {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					margin-right: 15rpx;
				}
			}
		}

		.course-info {
			width: 100%;
			margin: 20rpx 0;
			@include flex-center(center, left);

			view {
				margin-right: 30rpx;
				font-size: 30rpx;
				color: #fff;
			}
		}

		.course-header {
			width: 100%;
			height: 90rpx;
			border-bottom: 1px solid #333;
			@include flex-center(center, space-between);

			.course-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #fff;
			}

			.course-status {
				font-size: 24rpx;
				color: #fff;
				border-radius: 20rpx;
				padding: 6rpx 20rpx;
				@include flex-center();
			}
		}
	}

	.tabs {
		width: 100%;
		height: 150rpx;
		overflow: hidden;
		margin: 50rpx auto 30rpx;
		@include rounded-box(20rpx, #1f1f1f);
		@include flex-center(center, space-between);

		.tab {
			flex: 1;
			height: 100%;
			color: #aaa;
			font-size: 34rpx;
			@include flex-center();
		}

		.booking-tab-active {
			background-color: #FFD700;
			color: #000;
			font-weight: bold;
		}
	}

	.curriculumManagement {
		width: 680rpx;
		min-height: 100vh;
		margin: 30rpx auto;

		.section-title {
			width: 100%;
			@include flex-center(center, space-between);

			.title-display {
				color: #FFD700;
				font-size: 46rpx;
				font-weight: bold;
			}

			.date-display {
				color: #e0e0e0;
				font-size: 32rpx;
			}
		}
	}
</style>